package net.gyapp.markim.module.message;

import android.Manifest;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.easyder.wrapper.base.adapter.ViewHelper;
import com.easyder.wrapper.base.listener.OnViewHelper;
import com.easyder.wrapper.base.view.WrapperStatusFragment;
import com.easyder.wrapper.core.model.BaseVo;
import com.easyder.wrapper.core.scheduler.Task;
import com.easyder.wrapper.core.scheduler.TaskScheduler;
import com.gyf.barlibrary.ImmersionBar;
import com.luck.picture.lib.permissions.RxPermissions;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import net.gyapp.markim.R;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.core.ImPrivateUtils;
import net.gyapp.markim.core.entity.ConversationEntity;
import net.gyapp.markim.module.basic.MainActivity;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.basic.event.AccountChanged;
import net.gyapp.markim.module.basic.event.AccountIml;
import net.gyapp.markim.module.basic.event.MessageChanged;
import net.gyapp.markim.module.basic.event.MessageIml;
import net.gyapp.markim.module.contact.ContactAddActivity;
import net.gyapp.markim.module.contact.GroupAddActivity;
import net.gyapp.markim.module.message.adapter.MessageAdapter;
import net.gyapp.markim.module.mine.QrScanActivity;
import net.gyapp.markim.widget.WrapperPopWindow;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.winds.widget.autolayout.utils.AutoUtils;
import me.winds.widget.usage.TitleView;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;


/**
 * Auther:  winds
 * Data:    2018/2/27
 * Version: 1.0
 * Desc:    消息
 */


public class MessageFragment extends WrapperStatusFragment<CommonPresenter> {
    @BindView(R.id.title)
    TitleView title;
    @BindView(R.id.status_bar_view)
    View statusBarView;
    @BindView(R.id.mRecyclerView)
    SwipeMenuRecyclerView mRecyclerView;

    MessageAdapter adapter;
    WrapperPopWindow popupWindow;

    public static MessageFragment newInstance() {
        return new MessageFragment();
    }

    @Override
    public int getViewLayout() {
        return R.layout.fragment_message;
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        ImmersionBar.with(this).init();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ImmersionBar.with(this).statusBarView(statusBarView).init();
        initTitle();
        adapter = new MessageAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecyclerView.setSwipeMenuCreator(new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
                int size = AutoUtils.getPercentWidthSize(230);
                SwipeMenuItem item_delete = new SwipeMenuItem(_mActivity)
                        .setBackgroundColor(ContextCompat.getColor(_mActivity, R.color.colorRed))
                        .setText("删除")
                        .setTextColor(Color.WHITE)
                        .setTextSize(16)
                        .setWidth(size)
                        .setHeight(MATCH_PARENT);
                swipeRightMenu.addMenuItem(item_delete);
            }
        });
        mRecyclerView.setSwipeMenuItemClickListener(new SwipeMenuItemClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge) {
                menuBridge.closeMenu();
                ConversationEntity item = adapter.getItem(menuBridge.getAdapterPosition());
                clearCache(item);
            }
        });
        mRecyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                ConversationEntity item = adapter.getItem(position);
                startActivity(ConversationActivity.getIntent(_mActivity, item));
            }
        });

    }


    @Override
    protected void loadData(Bundle savedInstanceState) {
        refresh();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
    }

    @Override
    public void showContentView(String url, BaseVo dataVo) {

    }

    @Override
    public void onDestroy() {
        ImmersionBar.with(this).destroy();
        super.onDestroy();
    }

    @Override
    protected boolean isLazyLoad() {
        return false;
    }

    @Subscribe
    public void messageChanged(MessageChanged changed) {
        if (changed.sign == MessageIml.SIGN_CONVERSATION_REFRESH) {
            refresh();
        }
        if (changed.sign == MessageIml.SIGN_MESSAGE_RECALL) {
            refresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void accountChanged(AccountChanged changed) {
        if (changed.sign == AccountIml.ACCOUNT_CLEAR_CONVERSATION_CACHE || changed.sign == AccountIml.ACCOUNT_CONTACT_INFO_CHANGED) {
            refresh();
        }
    }

    private void refresh() {
        TaskScheduler.execute(new Task<List<ConversationEntity>>() {
            @Override
            public List<ConversationEntity> doInBackground() throws InterruptedException {
                return ImHelper.getConversationList();
            }

            @Override
            public void onSuccess(List<ConversationEntity> result) {
                adapter.setNewData(result);
                setUnReadCount(adapter.getUnReadCount());
            }
        });
    }

    /**
     * 设置未读消息数目
     *
     * @param count
     */
    private void setUnReadCount(int count) {
        if (_mActivity != null && !_mActivity.isFinishing() && _mActivity instanceof MainActivity) {
            ((MainActivity) _mActivity).setBedgeText(0, count);
        }
    }

    private void initTitle() {
        title.setCenterText("消息");
        title.findViewById(R.id.title_iv_left).setVisibility(View.GONE);
//        title.setRightImage(R.drawable.msg_add);
        title.setRightImage(R.drawable.add_title);
        title.setChildClickListener(R.id.title_iv_right, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFunctionPop(title);
            }
        });
    }


    private void showFunctionPop(View view) {
        popupWindow = new WrapperPopWindow.PopupWindowBuilder(getActivity())
                .setView(getHelperView(null, R.layout.pop_msg_fun, new OnViewHelper() {
                    @Override
                    public void help(ViewHelper helper) {
                        helper.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                switch (v.getId()) {
                                    case R.id.layout_scan:
                                        checkCameraPermission();
                                        break;
                                    case R.id.layout_add_friend:
                                        startActivity(ContactAddActivity.getIntent(_mActivity));
                                        break;
                                    case R.id.layout_add_group:
                                        startActivity(GroupAddActivity.getIntent(_mActivity));
                                        break;
                                    case R.id.layout_pop_parent:
                                        popupWindow.dissmiss();
                                        break;
                                }
                                popupWindow.dissmiss();
                            }
                        }, R.id.layout_scan, R.id.layout_add_friend, R.id.layout_add_group, R.id.layout_pop_parent);
                    }
                }))
                .size(AutoUtils.getPercentWidthSize(395), AutoUtils.getPercentHeightSize(512))
                .create().showAsDropDown(view, AutoUtils.getPercentWidthSize(700), 2);
    }

    private void checkCameraPermission() {
        new RxPermissions(_mActivity).request(Manifest.permission.CAMERA)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (!aBoolean) {
                            showToast("权限被拒绝");
                        }
                        onPermissionGain(aBoolean);
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast("申请权限出错");
                        onPermissionGain(false);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void onPermissionGain(Boolean aBoolean) {
        if (aBoolean) {
            startActivity(QrScanActivity.getIntent(_mActivity));
        }
    }

    private void clearCache(final ConversationEntity entity) {
        TaskScheduler.execute(new Task<Boolean>() {
            @Override
            public Boolean doInBackground() throws InterruptedException {
                ImPrivateUtils.clearCache(entity.id);
                return true;
            }

            @Override
            public void onSuccess(Boolean result) {

            }
        });
    }
}
